package com.lwl.concurrency.executor;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by liwenlong on 2018/1/7 14:04
 */
public class ExecutorTest1 {

    static class Task implements Runnable {
        private Date initDate;
        private String name;

        Task(String name) {
            initDate = new Date();
            this.name = name;
        }

        @Override
        public void run() {
            System.out.printf("%s: task %s: created on: %s\n", Thread.currentThread().getName(), name, initDate);
            long duration = 3;
            System.out.printf("%s: task %s: doing a task during %d seconds\n", Thread.currentThread().getName(), name, duration);
            try {
                TimeUnit.SECONDS.sleep(duration);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("%s: task %s finished on: %s\n", Thread.currentThread().getName(), name, new Date());
        }
    }


    static class Server {
        private ThreadPoolExecutor executor;

        Server() {
            executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        }

        void executeTask(Task task) {
            System.out.println("server: A new task has arrived");
            executor.execute(task);
            System.out.printf("Server:pool size: %d\n", executor.getPoolSize());
            System.out.printf("Server:Active count: %d\n", executor.getActiveCount());
            System.out.printf("Server:Completed tasks : %d\n", executor.getCompletedTaskCount());
        }

        void endServer() {
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程全部执行完成后的线程池数量: "+executor.getPoolSize());
            executor.shutdown();
            System.out.println("线程全部执行完成后的线程池终断: "+executor.isTerminated());
        }

    }

    public static void main(String[] args) {
        Server server = new Server();
        for (int i = 0; i < 100; i++) {
            Task task = new Task("Task-"+i);
            server.executeTask(task);
        }
        server.endServer();
    }

}
